<template>
  <div class="dashboard-container">
    <div class="digital-campus">
      <!-- 主标题 -->
        <div class="main-title">
          <h1>Digital Campuses</h1>
          <h2>数智交大</h2>
        </div>

      <!-- 数据卡片容器 -->
        <div class="stats-container" >
        <div 
          class="stat-item"
          v-for="(item, index) in statsData"
          :key="index"
        >
          <div class="stat-value">{{ item.value }}</div>
          <div class="stat-title">{{ item.title }}</div>
        </div>
      </div>
    </div>
    <!-- 顶部指标卡 -->
    <div class="indicator-row">
      <el-card 
        v-for="(item, index) in indicators"
        :key="index"
        class="indicator-card"
        shadow="hover"
      >
        <div class="card-content">
          <i :class="item.icon" :style="{color: item.color}"></i>
          <div class="card-text">
            <div class="title">{{ item.title }}</div>
            <div class="value">{{ item.value }}<span v-if="item.unit">{{ item.unit }}</span></div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 核心分析区 -->
    <div class="main-charts">
      <!-- 课程信息列表 -->
      <el-card class="chart-card">
         <!--表单-->
        <div class="app-container" style="width: 100%">
          <el-table
            v-loading="listLoading"
            :data="list"
            element-loading-text="Loading"
            border
            fit
            highlight-current-row
          >
            <el-table-column align="center" label="课程id"  prop="subId"/>
            <el-table-column align="center" label="课程名"  prop="subName"/>
            <el-table-column align="center" label="学分"  prop="subCode"/>
            <el-table-column align="center" label="学时"  prop="subAttribute"/>
            <el-table-column align="center" label="课程属性"  prop="subTime"/>
            <el-table-column align="center" label="课程类别"  prop="courseType"/>
          </el-table>
          <el-pagination
            background layout="prev, pager, next"
            v-show="total > 0"
            :total="total"
            :current-page.sync="queryParams.pageNum"
            :page-size.sync="queryParams.pageSize"
            @current-change="handleSuccess"
          />
        </div>
      </el-card>

      <!-- 右侧分布分析 -->
      <div class="right-charts">
              <!-- 学期筛选 -->
      <div class="filter-container">
        <el-select 
          v-model="query.semester" 
          @change="handleSemesterChange"
          placeholder="请选择学期"
          size="small"
        >
          <el-option
            v-for="(semester,index) in semesterOptions"
            :key="index"
            :label="semester"
            :value="semester"
          />
        </el-select>
      </div>
        <el-card class="chart-card">
          <div ref="scoreDistChart" class="chart"></div>
        </el-card>
        <el-card class="chart-card">
          <div ref="evaluationChart" class="chart"></div>
        </el-card>
      </div>
    </div>

    <!-- 底部对比分析 -->
    <!-- <div class="bottom-charts">
      <el-card class="chart-card">
        <div ref="courseRankChart" class="chart"></div>
      </el-card>
      <el-card class="chart-card">
        <div ref="teacherRadarChart" class="chart"></div>
      </el-card>
    </div> -->

  </div>
</template>

<script>
import * as echarts from 'echarts'
import { getDashboardData ,getOne,getTwo} from '@/api/dashboard'
import { getCourse } from '@/api/table'
import { getSemester1 } from '@/api/dashboard'

export default {
  data() {
    return {
            // 新增学期选项
      semesterOptions: [],
      //列表
      total:0,
      list: [],//列表
      queryParams:{
        pageNum:1,
        pageSize:15,
      },
      listLoading: false,
      indicators: [
        { title: '学生数', value: 0, unit: '人', icon: 'el-icon-user', color: '#36a3f7' },
        { title: '授课教师', value: 0, unit: '人', icon: 'el-icon-s-custom', color: '#34bfa3' },
        { title: '课程数', value: 0, unit: '门', icon: 'el-icon-trophy', color: '#f4516c' },
      ],
      charts: {
        trend: null,
        scoreDist: null,
        evaluation: null,
        courseRank: null,
        teacherRadar: null
      },
      chartData:{
        scoreDistribution:[],
        evaluationLevels:[]
      },
      statsData: [
        { value: '17 项', title: '国家科技成果奖' },
        { value: '7 个', title: '博士学位授权点' },
        { value: '21 个', title: '国家级一流本科专业建设点' },
        { value: '12 门', title: '国家级一流本科课程' },
        { value: '56 项', title: '2024年获国家自然科学基金项目' },
        { value: '260 余项', title: '国家级大学生创新创业项目' }
      ],
      query:{
        semester:"2023-2024-1",
      }
    }
  },

  mounted() {
    this.initCharts()
    this.loadData()
    window.addEventListener('resize', this.handleResize)
  },

  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize)
    Object.values(this.charts).forEach(chart => chart && chart.dispose())
  },

  methods: {
        // 新增学期变更处理
    handleSemesterChange() {
      this.loadChartData()
    },
        // 拆分图表数据加载方法
    async loadChartData() {
      try {
        const res1 = await getOne(this.query)
        const res2 = await getTwo(this.query)
        this.chartData.scoreDistribution = res1.data
        this.chartData.evaluationLevels = res2.data
        this.renderCharts(this.chartData)
      } catch (error) {
        this.$message.error('图表数据加载失败')
      }
    },
    handleSuccess(){
        getCourse(this.queryParams).then(res=>{
          this.list=res.data.rows
          this.total=res.data.total
        })
    },
    async loadData() {
      try {
        const res = await getDashboardData();
        this.updateIndicators(res.data)
        getCourse(this.queryParams).then(res=>{
          this.list=res.data.rows
          this.total=res.data.total
          
        })
        this.loadChartData()
        getSemester1().then(res=>{
          this.semesterOptions=res.data
        })
        this.renderCharts(this.chartData)
      } catch (error) {
        this.$message.error('数据加载失败')
      }
    },



    updateIndicators(data) {
      this.indicators.forEach((item, index) => {
        if(index==0)
        {
          item.value = data.studentNum          
        }
        if(index==1){
          item.value = data.teacherNum
        }
        if(index==2){
          item.value = data.courseNum
        }
      })
    },

    initCharts() {
      // this.charts.trend = echarts.init(this.$refs.trendChart)
      this.charts.scoreDist = echarts.init(this.$refs.scoreDistChart)
      this.charts.evaluation = echarts.init(this.$refs.evaluationChart)

    },

    renderCharts(data) {
      // 成绩及格率图表
      const scoreData = data.scoreDistribution
        .sort((a, b) => a.passRate - b.passRate)
        .slice(0, 10)
      
      this.charts.scoreDist.setOption({
        title: { text: '课程及格率排名（最低TOP10）', left: 'center' },
        tooltip: {
          trigger: 'axis',
          formatter: '{b}<br/>及格率：{c}%'
        },
        grid: {
          left: '20%',
          right: '10%'
        },
        xAxis: {
          type: 'value',
          axisLabel: {
            formatter: '{value}%'
          }
        },
        yAxis: {
          type: 'category',
          data: scoreData.map(item => item.subName),
          axisLabel: {
            interval: 0,
            width: 150,
            overflow: 'truncate'
          }
        },
        series: [{
          type: 'bar',
          data: scoreData.map(item => (item.passRate * 100).toFixed(1)),
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
              { offset: 0, color: '#ff9a8a' },
              { offset: 1, color: '#ff6b6b' }
            ])
          },
          label: {
            show: true,
            position: 'right',
            formatter: '{c}%'
          }
        }]
      })

      // 课程评教分数图表
      const evalMap = data.evaluationLevels.reduce((map, item) => {
        const key = item.subId
        if (!map[key]) {
          map[key] = {
            subName: item.subName,
            total: 0,
            count: 0
          }
        }
        map[key].total += parseFloat(item.evaScore)
        map[key].count++
        return map
      }, {})

      const evalData = Object.values(evalMap)
        .map(item => ({
          subName: item.subName,
          avgScore: item.total / item.count
        }))
        .sort((a, b) => a.avgScore - b.avgScore)
        .slice(0, 10)

      this.charts.evaluation.setOption({
        title: { text: '课程评教分数排名（最低TOP10）', left: 'center' },
        tooltip: {
          trigger: 'axis',
          formatter: '{b}<br/>平均分：{c}'
        },
        grid: {
          left: '20%',
          right: '10%'
        },
        xAxis: {
          type: 'value',
          min: function(value) {
            return Math.floor(value.min - 5)
          }
        },
        yAxis: {
          type: 'category',
          data: evalData.map(item => item.subName),
          axisLabel: {
            interval: 0,
            width: 150,
            overflow: 'truncate'
          }
        },
        series: [{
          type: 'bar',
          data: evalData.map(item => item.avgScore.toFixed(1)),
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
              { offset: 0, color: '#6fa8dc' },
              { offset: 1, color: '#3d85c6' }
            ])
          },
          label: {
            show: true,
            position: 'right',
            formatter: '{c}'
          }
        }]
      })
    },

    handleResize() {
      Object.values(this.charts).forEach(chart => chart.resize())
    }
  }
}
</script>

<style lang="scss" scoped>
.dashboard-container {
  padding: 20px;
  background: #f5f7fa;
}

.indicator-row {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
  gap: 16px;
  margin-bottom: 20px;

  .indicator-card {
    transition: transform 0.3s;

    &:hover {
      transform: translateY(-5px);
    }
  }

  .card-content {
    display: flex;
    align-items: center;
    padding: 20px;

    i {
      font-size: 32px;
      margin-right: 15px;
    }

    .card-text {
      .title {
        color: #909399;
        font-size: 14px;
      }

      .value {
        font-size: 24px;
        font-weight: bold;
        color: #303133;

        span {
          font-size: 14px;
          margin-left: 4px;
        }
      }
    }
  }
}

.main-charts {
  display: grid;
  grid-template-columns: 2fr 1fr;
  gap: 20px;
  margin-bottom: 20px;

  .chart {
    height: 400px;
  }
}

.bottom-charts {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;

  .chart {
    height: 350px;
  }
}

.chart-card {
  margin-bottom: 0;
  box-shadow: 0 2px 12px rgba(0,0,0,0.06);

  ::v-deep .el-card__body {
    padding: 20px;
  }
}

@media (max-width: 1200px) {
  .main-charts, .bottom-charts {
    grid-template-columns: 1fr;
  }

  .chart {
    height: 300px !important;
  }
}






.digital-campus {
  max-width: 2200px;
  margin: 0 auto;
  padding: 40px 20px;
}

.main-title {
  text-align: center;
  margin-bottom: 50px;
}

.main-title h1 {
  font-size: 2.5rem;
  color: #333;
  margin-bottom: 10px;
}

.main-title h2 {
  font-size: 1.8rem;
  color: #666;
}

.stats-container {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 30px;
}

.stat-item {
  text-align: center;
  padding: 25px;
  background: #f8f9fa;
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}

.stat-value {
  font-size: 2.2rem;
  font-weight: bold;
  color: #2c3e50;
  margin-bottom: 15px;
}

.stat-title {
  font-size: 1.1rem;
  color: #666;
  line-height: 1.4;
}

@media (max-width: 768px) {
  .stats-container {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 480px) {
  .stats-container {
    grid-template-columns: 1fr;
  }
  
  .main-title h1 {
    font-size: 2rem;
  }
  
  .main-title h2 {
    font-size: 1.5rem;
  }
}


// 新增筛选容器样式
.filter-container {
  margin-bottom: 20px;
  text-align: right;
  
  .el-select {
    width: 240px;
  }
}

.right-charts {
  display: flex;
  flex-direction: column;
  gap: 20px;
}
</style>